from django.shortcuts import render, HttpResponse, redirect
from App01 import models


# Create your views here.
def Login(request):
    if request.method == "POST":
        usr = request.POST.get('user')
        pwd = request.POST.get('pwd', None)
        try:
            user_obj = models.User.objects.get(username=usr)
        except Exception:
            return HttpResponse('用户名不正确')
        if user_obj and pwd == user_obj.password:
            return redirect('/Index/')
        else:
            return HttpResponse('密码不正确')
    return render(request, 'login.html')


def Index(request):
    return render(request, "index.html")


def publisher_list(request):
    ret = models.Publisher.objects.all()
    return render(request, 'publisher_list.html', {'publisher_list': ret})


def add_publisher(request):
    if request.method == 'POST':
        new_name = request.POST.get('publishername', None)
        if new_name:
            models.Publisher.objects.create(name=new_name)
            return redirect('/publisher_list/')
        else:
            error_msg = '出版社名称不能为空'
            return render(request, 'add_publisher.html', {'error': error_msg})
    return render(request, 'add_publisher.html')


def del_publisher(request):
    del_id = request.GET.get("id", None)
    if del_id:
        del_obj = models.Publisher.objects.get(id=del_id)
        del_obj.delete()
        return redirect("/publisher_list/")
    else:
        return HttpResponse("要删除的数据不存在!")


def edit_publisher(request):
    if request.method == "POST":
        edit_id = request.POST.get("id")
        new_name = request.POST.get("publisher_name")
        edit_publisher = models.Publisher.objects.get(id=edit_id)
        edit_publisher.name = new_name
        edit_publisher.save()
        return redirect("/publisher_list/")

    edit_id = request.GET.get("id")
    if edit_id:
        publisher_obj = models.Publisher.objects.get(id=edit_id)
        return render(request, "edit_publisher.html", {"publisher": publisher_obj})
    else:
        return HttpResponse("编辑的出版社不存在!")
